from flask import Blueprint,request,jsonify
from db import db1
from utils.acl import acl
import json
from utils.rs import rs
from utils.jwtc import myjwt
from utils.rabc import rbac
from utils.myfile import get_data
import time
import datetime
bp_user = Blueprint('user',__name__)

@bp_user.route('/login',methods=['GET','POST'])
def login():
    data = get_data()
    # 用户账号与密码
    username = data['username']
    password = data['password']
    # 判断用户名与密码是否正确
    sql = "select * from users where username='{}' and password='{}'".format(username,password)
    res = db1.find(sql)
    if not res:
        # 不存在直接返回
        return jsonify({'code':200,'msg':'用户名或密码错误,请重新输入'})
    starttime = time.time()
    # 生成token
    data = {'data': {"username": res['username'], 'uid': res['id'], "iat": starttime, "exp": 3600}}
    token = myjwt.jwt_en(data)
    # 获取用户页面权限
    pagelist = acl.get_page_reslist(res['id'])
    # 获取接口页面权限
    interfacelist = acl.get_interface_relist(res['id'])
    # 用户对应的角色对应的资源
    key = 'interfacelist'+str(res['id'])
    rs.insert_set(key,interfacelist)
    return jsonify({'code':200,'token':token,'pagelist':pagelist,'userid':res['id'],'username':res['username']})

@bp_user.route('/roleM')
def roleM():
    return 'rolem'

# @bp_user.route('/test')
# def test1():
#     key='abac'
#     rs.insert_hash(key,'ip','127.0.0.1')
#     rs.insert_hash(key,'level','003')
#     rs.insert_hash(key,'time',"['2021-10-10','2021-12-10']")
#     values = rs.get_all_hash(key)
#     for (k,v) in values.items():
#         if str(k,encoding='utf8') == 'time':
#             print('sf')
#             print(eval(v))
#             print(eval(v)[0])
#             print(eval(v)[1])
#     return 'ok'




def getresdata(data):
    # 把顶级拿出来放到列表中
    list = []
    idlist=[]
    for i in data:
        id = i['pid']
        if id not in idlist:
            list.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    # 变理顶级列表，在遍历数据，把子类加到顶级列表
    for j,value in enumerate(list):
        for i in data:
            if value['id'] == i['pid']:
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list



@bp_user.route('/getResource')
def getResource():
    uid = 1
    res = acl.get_resource(uid,1)
    mes = getresdata(res)
    return jsonify({'list':mes})


@bp_user.route('/role')
def role():
    sql = "select * from role"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


@bp_user.route('/resource')
def resource():
    id = request.args.get('id')
    print(id)
    if id:
        sql = "select resource from role_resource where roleid={}".format(id)
        res = db1.find_all(sql)
        list = []
        for i in res:
            list.append(i['resource'])
    else:
        time.sleep
        sql = "select * from resource"
        list = db1.find_all(sql)
    return jsonify({'code':200,'list':list})


@bp_user.route('/role_resource',methods=['POST','GET'])
def role_resource():
    if request.method == 'POST':
        data = get_data()
        id = request.args.get('id')
        sql = "delete from role_resource where roleid={}".format(int(id))
        db1.update(sql)
        ids = []
        for i in data:
            ids.append(i)
        for i in ids:
            sql1 = "insert into role_resource(roleid,resource) values({},{})".format(int(id),i)
            db1.update(sql1)
        return jsonify({'code':200,'msg':'配置成功'})


def getPor(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kargs):
        # 获取token
        token = request.headers['Token']
        # 解析token
        payload = myjwt.jwt_de(token)
        uid = payload['data']['uid']
        # 根据uid查询职务编号
        sql = "select dutys.coding as coding from dutys left join users on dutys.id=users.dutys_id where users.id=%d" %int(uid)
        res = db1.find(sql)
        if res['coding'] == '003':
        # 获取当前ip地址
            ip = request.remote_addr
            # 获取当前日期
            time = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d')
            values = r.get_all_hash_params('abac')
            for k,v in values.items():
                value = str(v,encoding='utf8')
                key = str(k,encoding='utf8')
                if key == 'ip':
                    if value != ip:
                        return jsonify({'code':401,'msg':'ip无权限'})
                if key == 'time':
                    timev = eval(r.get_hash_params('abac','time'))
                    if time<timev[0] or time>timev[1]:
                        return jsonify({'code':4001,'msg':'无时间权限'})
        #     读取限制
            if request.method != "GET":
                return jsonify({'code':4010,'msg':'无法读取'})

        return fun(*args,**kargs)
    return wrapper


@bp_user.route('/user_res')
def user_res():
    user_id = request.args.get('user_id')
    sql = "select resourceid from user_resource where user_id=%d"%int(user_id)
    res = db1.find_all(sql)
    list1 = []
    for i in res:
        list1.append(i['resourceid'])
    return jsonify({'code':200,'list':list1})



@bp_user.route('/config_user_role',methods=['POST','GET'])
def config_user_role():
    data = request.json
    user_role.update_user_role(data['userid'],data['urlist'])
    return jsonify({'code':200})